package com.yjd.comm.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

/**
 * @ClassName: TxtFileCacheUtil
 * @Description: txt文件缓存
 * @author ready likun_557@163.com
 * @date 2014-8-19 下午2:37:12
 */
public class TxtFileCacheUtil {
	static class TxtModel {
		private long lastModifyTime;
		private List<String> strList;

		private TxtModel(long lastModifyTime, List<String> strList) {
			super();
			this.lastModifyTime = lastModifyTime;
			this.strList = strList;
		}

		public long getLastModifyTime() {
			return lastModifyTime;
		}

		public void setLastModifyTime(long lastModifyTime) {
			this.lastModifyTime = lastModifyTime;
		}

		public List<String> getStrList() {
			return strList;
		}

		public void setStrList(List<String> strList) {
			this.strList = strList;
		}

	}

	private static Logger logger = Logger.getLogger(TxtFileCacheUtil.class);
	private static Map<String, TxtModel> proCachedMap = new HashMap<String, TxtModel>();

	/**
	 * 获取某个txt中所有的数据，数据放在map中
	 * 
	 * @param txtFile
	 * @return
	 */
	public static List<String> get(String txtFile) {
		File file = getFile(txtFile);
		TxtModel tm = proCachedMap.get(txtFile);
		if (tm != null && tm.getLastModifyTime() != file.lastModified()) {
			proCachedMap.remove(txtFile);
		}
		tm = proCachedMap.get(txtFile);
		if (tm == null) {
			synchronized (proCachedMap) {
				tm = proCachedMap.get(txtFile);
				if (tm == null) {
					put(txtFile);
					tm = proCachedMap.get(txtFile);
				}
			}
		}
		return tm == null ? null : tm.getStrList();
	}

	/**
	 * 获取资源文件指定的文件
	 * 
	 * @param propertiesFile
	 * @return
	 */
	public static File getFile(String propertiesFile) {
		return new File(PropertiesCacheUtil.class.getClassLoader()
				.getResource(propertiesFile).getPath());
	}

	public static List<String> put(String propertiesFile) {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(
					PropertiesCacheUtil.class.getClassLoader()
							.getResourceAsStream(propertiesFile)));
			List<String> strings = new ArrayList<String>();
			String string = null;
			while ((string = reader.readLine()) != null) {
				strings.add(string);
			}
			proCachedMap.put(propertiesFile,
					new TxtModel(getFile(propertiesFile).lastModified(),
							strings));
			return strings;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
					throw new RuntimeException(e);
				}
			}
		}
	}
}
